package config

import (
	"encoding/json"
	"errors"
	"os"

	"github.com/getkin/kin-openapi/openapi3"
	"github.com/invopop/yaml"
	"github.com/sirupsen/logrus"
)

type OpenAPI struct {
	//常见api定义文件
	Welknown string `goblet:"wellknown,wellknown.yaml"`
	//自己的api定义文件
	Api     string `goblet:"api,api.yaml"`
	Append  bool   `goblet:"append,false"`
	Encrypt bool   `goblet:"encrypt,true"`
}

func (o *OpenAPI) LoadDefinition() (*openapi3.T, error) {
	if o.Api != "" {
		return openapi3.NewLoader().LoadFromFile(o.Api)
	}
	return nil, errors.New("no openapi definition found")
}

func (o *OpenAPI) NewDefaultDefinition() (*openapi3.T, error) {
	def, err := openapi3.NewLoader().LoadFromData([]byte(`
info:
  title: 默认API定义文件
  version: 1.0.0
  description: 请按实际API定义修改此文件
openapi: 3.0.0
`))
	if err == nil {
		if !o.Append {
			logrus.Error("已创建默认API定义文件，请按实际API定义修改此文件，设置openapi.append=true以追加模式启动，追加模式可将收到的未知API定义追加到定义文件中")
		}
		err = SaveYaml(def, o.Api)
	}
	return def, err
}

// SaveYaml 保存yaml文件
func SaveYaml(def *openapi3.T, name string) error {
	bts, err := json.Marshal(def)
	if err == nil {
		bts, err = yaml.JSONToYAML(bts)
		if err == nil {
			return os.WriteFile(name, bts, 0600)
		}
	}
	return err
}
